<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item v-text="$props.title"></el-breadcrumb-item>
    </el-breadcrumb>
    <el-button type="primary" plain @click="dialogFormVisible=true;formAction=2;form={};" style="margin: 20px;"
      size="small">添加</el-button>
    <!-- 刷新按钮 -->
    <el-button size="small" style="float: right;" @click="getPage(currentPage, perPage)"><i class="el-icon-refresh"></i></el-button>

    <!-- 表格渲染 -->
    <el-table
      v-loading="loading"
      element-loading-text="拼命加载数据中"
      element-loading-spinner="el-icon-loading"
      :data="tableData.filter(data => !search || data[$props.searchProp].toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%;">

      <!-- 读取列动态属性 -->
      <el-table-column v-for="(item, index) in column" :label="item.label" :prop="item.prop" :key="index"
        :formatter="(row, column, cellValue) => formatData(row, column, cellValue, item)">
      </el-table-column>

      <!-- 功能列 -->
      <el-table-column align="right">
        <!-- 搜索框定义 -->
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" :placeholder="$props.searchText" />
        </template>

        <!-- 编辑和删除操作按钮 -->
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.$index, scope.row)"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 翻页器 -->
<!--    <el-pagination style="text-align: center; margin-top: 5%;" background layout="prev, pager, next"
      @current-change="handleCurrentChange" :total="count">
    </el-pagination> -->
    <Pagination
      :childMsg="{currentPage: currentPage, pageSize: perPage, total: count}"
      @callFather="(pageparm) => {this.currentPage = pageparm.currentPage;this.perPage = pageparm.pageSize;getPage(this.currentPage, this.perPage)}"></Pagination>


    <!-- 确认删除对话框 -->
    <el-dialog v-if="currentId" title="确定要删除吗" :visible="toDel" width="30%" :before-close="handleClose">
      <span>确定要删除吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="currentId = ''">取 消</el-button>
        <el-button type="primary" @click="del()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加、修改表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <!-- 输入框 -->
        <el-form-item v-for="(item, index) in column" :label="item.label" :label-width="formLabelWidth" :key=index>
          <el-input v-if="item.tagType=='input'" :type="item.type" v-model="form[item.prop]" autocomplete="off"
            :disabled="item.disable"></el-input>
          <!-- 时间选择器 -->
          <el-date-picker v-else-if="item.tagType=='timer'" v-model="form[item.prop]" :type="item.type"
            placeholder="选择日期时间" :disabled="item.disable">
          </el-date-picker>
          <!-- 选项框 -->
          <el-select v-else-if="item.tagType=='selector'" v-model="form[item.prop]" placeholder="请选择"
            :disabled="item.disable">
            <el-option v-for="i in item.options" :key="i.value" :label="i.label" :value="i.value">
            </el-option>
          </el-select>
          <!-- 计数器 -->
          <el-input-number v-else-if="item.tagType=='counter'" v-model="form[item.prop]" :min="1" :max="9999"
            label="描述文字" :disabled="item.disable"></el-input-number>
          <!-- 富文本编辑器 -->
          <vue-editor
            v-else-if="item.tagType=='editor'"
            id="editor"
            v-model="form[item.prop]"
            useCustomImageHandler
            @image-added="handleImageAdded"></vue-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;handleClose()">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>
  import { VueEditor } from "vue2-editor";
  import axios from 'axios';
  import Pagination from "./Pagination.vue";
  export default {
    components: {
      VueEditor,
      Pagination
    },
    name: 'CRUD',
    data() {
      return {
        // 表格加载情况
        loading: true,
        // 总数量
        count: 10,
        // 每页显示数量
        perPage: 5,
        // 面包屑标题
        navTitle: 'asd',
        // 列属性
        column: [
          {label: 'id', prop: 'id', disable: true, tagType: 'input',type: "text"},
          // {label: '比赛名', prop: 'gameName', disable: false, tagType: 'input',type: "text"},
          // {label: '决赛', prop: 'nextGame', disable: false, tagType: 'input',type: "text"},
          // {label: '性别', prop: 'gender', disable: false, tagType: 'selector',type: "text", options:[{label: '男', value: 1}, {label: '女', value: 0}]},
          // {label: '场地', prop: 'fieldId', disable: false, tagType: 'input',type: "text"},
          // {label: '限制人数', prop: 'maxPerson', disable: false, tagType: 'counter',type: "text"},
          // {label: '比赛状态', prop: 'status', disable: false, tagType: 'selector',type: "text", options:[{label: '报名中', value: 0}, {label: '截止报名', value: 1}, {label: '检录中', value: 2}, {label: '比赛中', value: 3}, {label: '结束', value: 4}]},
          // {label: '开始时间', prop: 'startTime', disable: false, tagType: 'timer',type: "datetime"},
          // {label: '结束时间', prop: 'endTime', disable: false, tagType: 'timer',type: "datetime"},
        ],
        // 富文本编辑器工具栏配置
        customToolbar: [
          ['bold', 'italic', 'underline'],
          [{
            'list': 'ordered'
          }, {
            'list': 'bullet'
          }],
          [{
            'indent': '-""'
          }, {
            'indent': '+""'
          }],
          [{
            'header': '2'
          }],
          ['clean'],
          [{
            'align': 'center'
          }, {
            'align': 'justify'
          }, {
            'align': 'right'
          }]
        ],
        // 表格数据
        tableData: [],

        search: '',
        currentPage: 1,
        toDel: false,
        dialogFormVisible: false,
        formAction: 1, // 1为编辑，2为添加
        currentId: '',
        index: -1,
        form: {},
        formLabelWidth: '120px'

      }
    },
    methods: {
      // 表格数据格式化
      formatData(row, column, cellValue, item) {
        if (item.tagType === 'selector') {
          for (var i = 0; i < item.options.length; i++) {
            if (item.options[i].value === cellValue) {
              return item.options[i].label;
            }
          }
        } else if (item.tagType === 'timer') {
          return "日:" + cellValue.replace("T", " 时:").replace(".000+00:00", "")
        } else if (item.tagType == 'editor') {
          return cellValue.slice(0, 10) + "...";
        }
        return cellValue;
      },
      update() {
        // console.log(this.formAction)
        if (this.formAction === 1) {
          // 编辑
          // console.log(this.formAction);
          this.Update(this.form).then(res => {
            this.$message({
              message: "更新成功！",
              type: "success"
            })
            this.$emit('refreshTree')
          });

        } else {
          // 添加
          // console.log(this.formAction);
          this.Add(this.form).then(res => {
            this.$message({
              message: res.msg,
              // message: res.data.msg,
              type: (res.code === 1) ? "success" : "error"
            })
            this.$emit('refreshTree')
          });
          // this.getPage(this.currentPage, this.perPage);
          // this.tableData.push(this.form);
        }

        this.index = -1;
        this.dialogFormVisible = false;
        this.form = {}
        this.getPage(this.currentPage, this.perPage);
      },
      getPage(page, pageSize) {
        // 获取表格数据
        this.loading = true
        this.List(page, pageSize).then(res => {
          this.tableData = res.data;
          this.count = res.count;
          this.loading = false;
        })
      },
      handleCurrentChange(val) {
        // 翻页
        console.log(`当前页: ${val}`);
        this.getPage(val, this.perPage);
      },
      handleEdit(index, row) {
        // 编辑操作
        this.index = index;
        this.formAction = 1;
        this.form = this.tableData[index];
        this.dialogFormVisible = true;


      },
      handleClose() {
        // 关闭对话框
        this.getPage(this.currentPage, this.perPage);
        this.$message({
          message: "取消修改！",
          type: "info"
        })
      },
      del() {
        // 删除
        this.Delete(this.currentId).then(res => {
          this.tableData.splice(this.index + 1, 1);
          this.$message({
            message: "删除成功",
            type: 'success'
          })
        });
        this.currentId = '';
        this.index = -1;

      },
      handleDelete(index, row) {
        // 打开删除对话框
        this.toDel = true;
        this.currentId = row.id;
        this.index = index;
      },
      handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
        // An example of using FormData
        // NOTE: Your key could be different such as:
        // formData.append('file', file)

        var formData = new FormData();
        formData.append("file", file);
        console.log("正在上传图片");
        axios({
            url: "https://www.tuchuangs.com/upload/localhost",
            method: "POST",
            data: formData
          })
          .then(result => {
            const url = result.data.url; // Get url from response
            Editor.insertEmbed(cursorLocation, "image", url);
            resetUploader();
            console.log(`imgUrl -> ${url}`);
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    props: {
      // 面包屑标题
      title: String,
      // 添加编辑对话框标题
      dialogTitle: String,
      // 数据列属性名
      stacolumn: Array,
      // 更新方法接口
      Update: Function,
      // 添加方法接口
      Add: Function,
      // 删除方法接口
      Delete: Function,
      // 查询方法接口
      List: Function,
      // 搜索字段属性名
      searchProp: String,
      // 搜索框提示文本
      searchText: String,
    },

    created() {
      // 初始化
      this.column = this.stacolumn;
      console.log(this.$props)
      this.getPage();

    }
  }
</script>
